package ycl.security.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.stereotype.Component;
import ycl.common.constants.RedisConstant;
import ycl.common.constants.SecurityConstant;
import ycl.common.models.res.LoginUser;
import ycl.common.utils.ServletUtil;
import ycl.security.entity.SecurityUser;
import ycl.security.feign.SystemFeign;
import ycl.security.service.LoginService;
import ycl.system.entity.SysUser;
import ycl.system.mapper.SysUserMapper;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 认证成功
 *
 * @author ycl
 * @date 2022-03-09 14:14:38
 */
@Component
@Slf4j
public class AuthSuccessHandler implements AuthenticationSuccessHandler {

	@Resource
	private SysUserMapper sysUserMapper;
	@Resource
	private SystemFeign systemService;
	@Resource
	private LoginService loginService;
	@Resource
	private StringRedisTemplate stringRedisTemplate;

	/**
	 * 认证
	 *
	 * @param request        req
	 * @param response       res
	 * @param authentication auth
	 */
	@Override
	public void onAuthenticationSuccess(
			HttpServletRequest request,
			HttpServletResponse response,
			Authentication authentication)
			throws IOException {
		log.info("AuthSuccessHandler . onAuthenticationSuccess . 认证检查通过");
		//认证对象身份, 返回验证主体
		SecurityUser user = (SecurityUser) authentication.getPrincipal();
		String username = user.getUsername();
		//获取当前用户信息
		WebAuthenticationDetails details = (WebAuthenticationDetails) authentication.getDetails();
		//获取用户
		SysUser sysUser = loginService.getUserByUsername(username);
		//查询用户的权限
		String loginType = request.getHeader(SecurityConstant.LOGIN_TYPE);
		LoginUser login = loginService.login(sysUser, loginType, details.getRemoteAddress());

		stringRedisTemplate.delete(RedisConstant.getUserLockKey(username));
		stringRedisTemplate.delete(RedisConstant.getUserLoginFailKey(username));
		ServletUtil.writeResponse(response, login);
	}

}
